package com.example.examsystem.service;

import com.example.examsystem.dto.PageResponse;
import com.example.examsystem.model.LogLevel;
import com.example.examsystem.model.SystemLog;
import com.example.examsystem.repository.SystemLogRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 系统日志服务
 */
@Service
@RequiredArgsConstructor
public class SystemLogService {
    
    private final SystemLogRepository systemLogRepository;
    
    /**
     * 异步保存日志
     */
    @Async
    public void saveLog(SystemLog systemLog) {
        try {
            systemLogRepository.save(systemLog);
        } catch (Exception e) {
            // 日志保存失败不应该影响主业务
            System.err.println("保存系统日志失败: " + e.getMessage());
        }
    }
    
    /**
     * 分页查询系统日志
     */
    public PageResponse<SystemLog> getLogs(int page, int size, String username, 
                                          LogLevel level, String action, 
                                          LocalDateTime startTime, LocalDateTime endTime) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt"));
        
        Page<SystemLog> logPage = systemLogRepository.findByQuery(
            username, level, action, startTime, endTime, pageable);
        
        return new PageResponse<>(
            logPage.getContent(),
            logPage.getNumber(),
            logPage.getSize(),
            logPage.getTotalElements(),
            logPage.getTotalPages()
        );
    }
    
    /**
     * 清理过期日志
     */
    public void cleanExpiredLogs(int days) {
        LocalDateTime expireTime = LocalDateTime.now().minusDays(days);
        systemLogRepository.deleteByCreatedAtBefore(expireTime);
    }
}
